package com.example.myapplication.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;

import java.util.List;

public class BannerTool02 extends PagerAdapter {
    private Context context;
    private List<Integer> list;
    private ImageView imageView;
    private ViewPager viewPager;

    @Override
    public int getCount() {
        return list != null?list.size():0;
    }

    public BannerTool02(Context context, List<Integer> list, ViewPager viewPager) {
        this.context = context;
        this.list = list;
        this.viewPager = viewPager;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(context).load(list.get(position)).into(imageView);
        container.addView(imageView);
        mHandler.sendEmptyMessageDelayed(0,3*1000);
        return imageView;
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int index = viewPager.getCurrentItem();
            index = (index + 1) % (list.size());
            viewPager.setCurrentItem(index);
            mHandler.sendEmptyMessageDelayed(0,3*1000);
        }
    };


    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

        container.removeView((View)object);
    }
}
